This post demonstrates how to
- Display a map from OpenStreetMaps using Folium
- Add custom shape files to define regions of interest
- Color the regions of interest based on data in a pandas dataframe
The code of this post is available at https://github.com/rsandstroem/IPythonNotebooks/blob/master/GeoMapsFoliumDemo/GeoMapsFoliumDemo.ipynb .
Using the method described here, you do not need any local map data. The maps are automatically pulled from OpenStreetMap.
However, you might want use concepts such as regions, and you need to define them through files containing those geolocations. There are multiple sources of data which is freely available, in this example we are using shape files from this location: http://data.geo.admin.ch.s3.amazonaws.com/ch.swisstopo.swissboundaries3d-kanton-flaeche.fill/data.zip
We have provided the shape files we will use for this demonstration, normally you would need to retrieve and unpack the map data.
There are many file formats commonly used for maps. In this case what we have are a set of shapefiles. Since we will be working with geojson files in this demonstration you need to convert them to geojson.
A sample geojson file has been supplied with this tutorial, but for reference you can create a geojson file from the shape files from a console like this:
ogr2ogr -f GeoJSON -t_srs EPSG:4326 switzerland.geojson swissBOUNDARIES3D_1_2_TLM_KANTONSGEBIET.shp
You now have a map in your local directory, formatted as a geojson file.
For this demonstration we need "folium". Install it using
pip install folium
or if you are using the Anaconda you can do
sudo conda install --channel https://conda.binstar.org/IOOS folium
where you can replace the channel with your choice from the options listed by
binstar search -t conda folium
from IPython.display import HTML
import folium
First we show the map without any use of the geojson we created from the shapefiles.
kanton_map = folium.Map(location=[46.8, 8.33],
tiles='Mapbox Bright', zoom_start=7)
kanton_map
You should now see an map of Switzerland with surrounding countries and cities. Next, display an OpenStreetMap and overlay the cantons of Switzerland on top.
kanton_map.choropleth(geo_path='switzerland.geojson')
kanton_map